<template>
  <div class="home">
    <van-nav-bar
      v-show="edit"
      title="我的信息"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- <van-nav-bar class="blue" title="入连人员自主报备" /> -->
    <!-- <img src="../../assets/images/rlzzbb.png" /> -->
    <van-form validate-first ref="formDataRef" @submit="onSubmit">
      <van-cell-group inset title="账户基本信息">
        <van-field name="radio" @click="userCheck()" label="用户类型">
          <template #input>
            <span v-if="edit">{{
              addManForm.sysUserBean.userType == '8' ? '学生' : '家长'
            }}</span>
            <van-radio-group
              v-show="!edit"
              v-model="addManForm.sysUserBean.userType"
              direction="horizontal"
            >
              <van-radio name="8">学生</van-radio>
              <van-radio name="9">家长</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-model="addManForm.sysUserBean.name"
          name="姓名"
          label="姓名"
          placeholder="姓名"
          :rules="rules.name"
        />

        <van-field
          v-model="addManForm.sysUserBean.cardno"
          name="身份证号"
          label="身份证号"
          placeholder="身份证号"
          :rules="rules.cardno"
          maxlength="18"
        />
        <van-field
          v-model="addManForm.sysUserBean.mobile"
          name="手机号码"
          label="手机号码"
          placeholder="手机号码"
          :rules="rules.mobile"
        />
        <van-field
          v-model="addManForm.sysUserBean.familyId"
          value="000001"
          name="家庭Id"
          label="家庭Id"
          placeholder="家庭Id"
          :rules="rules.cardno"
        />
        <div v-show="!edit">
          <van-field
            v-model="addManForm.sysUserBean.password"
            type="password"
            name="密码"
            label="密码"
            placeholder="密码"
            :rules="rules.password"
          />
          <van-field
            v-model="password"
            name="确认密码"
            label="确认密码"
            placeholder="确认密码"
          />
        </div>
      </van-cell-group>
      <!-- <van-field
        label="来连方式"
        v-model="formData.trave_mode"
        name="pattern"
        placeholder="请选择来连方式"
        @focus="showTrave = true"
        :rules="[{ required: true, message: '请选择来连方式' }]"
      /> -->
      <van-cell-group
        inset
        v-for="(item, index) in addManForm.userInfoBeanList"
        :model="addManForm"
        :key="index"
        title="学生信息"
      >
        <van-cell value="删除学生信息" v-show="gtjzrShow">
          <template #right-icon>
            <van-icon
              style="padding-right: 1rem"
              @click="pushResidentList()"
              name="plus"
              class="search-icon"
              >添加</van-icon
            >
            <van-icon
              @click="removeResident(index)"
              name="cross"
              class="search-icon"
              >删除</van-icon
            >
          </template>
        </van-cell>

        <van-field
          v-model="addManForm.userInfoBeanList[index].name"
          name="学生姓名"
          label="学生姓名"
          placeholder="学生姓名"
          :rules="rules.student"
        />
        <van-field
          v-model="addManForm.userInfoBeanList[index].cardno"
          name="身份证号"
          label="身份证号"
          placeholder="身份证号"
          :rules="rules.cardno"
          maxlength="18"
        />
        <van-field
          v-model="addManForm.userInfoBeanList[index].mobile"
          name="手机号"
          label="手机号"
          placeholder="手机号"
          :rules="rules.mobile"
        />

        <van-field
          v-model="addManForm.userInfoBeanList[index].schoolDistrictName"
          name="学校所属区"
          label="学校所属区"
          placeholder="学校所属区"
          @focus="showCode = true"
          :rules="rules.schoolDistrictName"
        />
        <van-popup v-model="showCode" round position="bottom">
          <van-picker
            show-toolbar
            :columns="showCodeColumns"
            value-key="name"
            @cancel="showCode = false"
            @confirm="val => onCodeConfirm(val, index)"
          />
        </van-popup>
        <van-field
          v-model="addManForm.userInfoBeanList[index].schoolName"
          name="学校名称"
          label="学校名称"
          placeholder="学校名称"
          @focus="showSchool = true"
          :rules="rules.schoolName"
        />
        <van-popup v-model="showSchool" round position="bottom">
          <van-picker
            show-toolbar
            :columns="showSchoolColumns"
            value-key="name"
            @cancel="showSchool = false"
            @confirm="val => onSchoolConfirm(val, index)"
          />
        </van-popup>

        <van-field
          v-model="addManForm.userInfoBeanList[index].className"
          name="班级"
          label="班级"
          placeholder="班级"
          @focus="showClass = true"
          :rules="rules.className"
        />
        <van-popup v-model="showClass" round position="bottom">
          <van-picker
            show-toolbar
            :columns="showClassColumns"
            value-key="name"
            @cancel="showClass = false"
            @confirm="val => onClassConfirm(val, index)"
          />
        </van-popup>

        <van-field
          v-model="addManForm.userInfoBeanList[index].addressProvince"
          readonly
          name="居住地"
          label="居住地"
          placeholder="点击选择居住地"
          @click="
            showArea2 = true
            selectedIndex = index
          "
          :rules="[{ required: true, message: '请选择正确内容' }]"
        />
        <van-popup v-model:show="showArea2" position="bottom">
          <van-area
            value="210200"
            :area-list="areaList"
            @confirm="val => enAreaConfirm(val, index)"
            @cancel="showArea2 = false"
          />
          <!-- enAreaConfirm(value,index) -->
        </van-popup>

        <van-field
          v-model="addManForm.userInfoBeanList[index].addressInfo"
          name="详细地址"
          label="详细地址"
          placeholder="详细地址"
          :rules="[{ required: true, message: '请填写详细地址' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          保存
        </van-button>
      </div>
    </van-form>
    <!-- 省市区弹出 -->
    <van-popup
      v-model="show"
      closeable
      position="bottom"
      :style="{ height: '100%' }"
    >
      <div class="container">
        <div
          class="item"
          v-for="(item, index) in forArea"
          :key="index"
          @click="checkoutArea(item)"
        >
          {{ item.name || item }}
        </div>
      </div>
    </van-popup>

    <!-- @confirm="onCodeConfirm" -->

    <!-- 日期 -->
    <van-popup v-model="showDate" round position="bottom">
      <van-datetime-picker
        @confirm="getConfirm"
        @cancel="showDate = false"
        :min-date="minDate"
        type="date"
        title="选择年月日"
      />
    </van-popup>
  </div>
</template>

<script>
import { areaList } from '@vant/area-data'
import area from '@/libs/area.json'
import {
  register,
  getSchoolList,
  getClassList,
  generateFamilyId,
  getUserInfo,
  editSysUserInfo
} from '@/api/student/register'
import { Toast, Dialog } from 'vant'
export default {
  data() {
    return {
      selectedIndex: '',
      edit: false,
      gtjzrShow: false,
      showTwoLabel: false,
      checked: false,
      goDlShow: false,
      showArea: false,
      showArea2: false,
      showClass: false,
      areaList,
      minDate: new Date(1900, 0, 1),
      showDate: false, // 选择生日
      seat_number_label: '',
      range_label: '',
      columns: ['身份证', '护照', '军官证', '港澳通行证'],
      trave_columns: ['飞机', '火车', '轮渡', '自驾', '客运'],
      sexColumns: ['男', '女'],
      show: false,
      forArea: [],
      password: '', // 密码
      showCodeColumns: [
        {
          name: '中山区',
          value: '210202'
        },
        {
          name: '西岗区',
          value: '210203'
        },
        {
          name: '沙河口区',
          value: '210204'
        },
        {
          name: '甘井子区',
          value: '210211'
        },
        {
          name: '旅顺口区',
          value: '210212'
        },
        {
          name: '金普新区',
          value: '210213'
        },
        {
          name: '高新园区',
          value: '210214'
        },
        {
          name: '长兴岛经济区',
          value: '210216'
        },
        {
          name: '长海县',
          value: '210224'
        },
        {
          name: '瓦房店市',
          value: '210281'
        },
        {
          name: '普兰店市',
          value: '210282'
        },
        {
          name: '庄河市',
          value: '210283'
        }
      ],
      showCode: false, // 学校所属区
      showSchool: false, // 学校名称
      showSchoolColumns: [], // 学校下拉列
      showClassColumns: [],
      addManForm: {
        sysUserBean: {
          cardno: '', // 身份证号
          name: '', // 姓名
          password: '', // 密码
          mobile: '', // 手机号码
          userType: '8', // "用户类型 8学生 9家长",
          familyId: ''
        },
        userInfoBeanList: [
          // 0学生 1家长
          {
            name: '',
            cardno: '',
            mobile: '',
            sex: '',
            addressProvince: '',
            addressCity: '',
            addressDistrict: '',
            addressInfo: '',
            schoolId: '',
            schoolName: '',
            classId: '',
            className: '',
            remark: '',
            schoolDistrictName: '',
            schoolDistrictId: ''
          }
        ]
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: ['blur', 'change']
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['blur', 'change']
          },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！' }
        ],
        cardno: [
          {
            required: true,
            message: '请输入身份证号',
            trigger: ['blur', 'change']
          }
        ],
        student: [
          {
            required: true,
            message: '请输入学生姓名',
            trigger: ['blur', 'change']
          }
        ],
        schoolDistrictName: [
          {
            required: true,
            message: '请选择学校区',
            trigger: ['blur', 'change']
          }
        ],
        schoolName: [
          {
            required: true,
            message: '请选择学校名称',
            trigger: ['blur', 'change']
          }
        ],
        className: [
          {
            required: true,
            message: '请选择班级',
            trigger: ['blur', 'change']
          }
        ],
        addressProvince: [
          {
            required: true,
            message: '请选择居住地',
            trigger: ['blur', 'change']
          }
        ],
        addressInfo: [
          {
            required: true,
            message: '请选详细地址',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  mounted() {
    if (this.$route.query.type == 'edit') {
      getUserInfo(this.$route.query.sysUserId).then(res => {
        if (res.data.errcode === 0) {
          this.addManForm = res.data.data
        } else {
          Toast.fail(res.data.msg)
        }
      })
      this.edit = true
    } else {
      generateFamilyId().then(res => {
        if (res.data.errcode === 0) {
          this.addManForm.sysUserBean.familyId = res.data.data.familyId
        } else {
          Toast.fail(res.data.msg)
        }
      })
      this.edit = false
    }
  },
  methods: {
    classList() {
      getClassList(this.addManForm).then(res => {
        Toast.clear()
        if (res.data.errcode === 0) {
        } else {
          Toast.fail(res.data.msg)
        }
      })
    },
    pushResidentList() {
      this.addManForm.userInfoBeanList.push({
        // user_info_id: this.$route.query.id,
        name: '',
        cardno: '',
        mobile: '',
        sex: '',
        addressProvince: '',
        addressCity: '',
        addressDistrict: '',
        addressInfo: '',
        schoolId: '',
        schoolName: '',
        classId: '',
        className: '',
        remark: '',
        schoolDistrictName: '',
        schoolDistrictId: ''
      })
    },
    removeResident(index) {
      if (index == 0) {
        Toast.fail('不能继续删除')
        return
      }
      this.addManForm.userInfoBeanList.splice(index, 1)
    },
    userCheck() {
      // this.addManForm.sysUserBean.userType = this.addManForm.addManForm.sysUserBean.userType
      if (this.addManForm.sysUserBean.userType == '8') {
        this.gtjzrShow = false
      } else if (this.addManForm.sysUserBean.userType == '9') {
        this.gtjzrShow = true
      }
    },
    delImg(index) {
      // 删除指定下标的图片对象
      if (isNaN(index) || index >= this.postData.length) {
        return false
      }
      let tmp = []
      for (let i = 0, len = this.postData.length; i < len; i++) {
        if (this.postData[i] !== this.postData[index]) {
          tmp.push(this.postData[i])
        }
      }
      this.postData = tmp
    },
    onRead(file) {
      // 上传图片到图片服务器
      // this.$refs.clothImg.src = file.content
      this.postData.push(file) // postData是一个数组
      // let url = API + '/upload?type=99'
      // let fd = new FormData()
      // fd.append('upImgs', file.file)
      // this.axios.post(url, fd, {headers: {
      //   'Content-Type': 'multipart/form-data'
      // }}).then(res => {
      //   this.imgUrlListValue.push(res.data.urls[0].image) //这里上传到指定的图片服务器，成功后会返回图片的url
      // }).catch(err => {
      //   alert(err)
      // })
    },
    getConfirm(value) {
      let yy = new Date(value).getFullYear()
      let mm = new Date(value).getMonth() + 1
      let dd = new Date(value).getDate()
      this.formData.bithday = yy + '-' + mm + '-' + dd
      this.showDate = false
    },
    onAreaConfirm(value) {
      this.showArea = false
      this.formData.start_addr_list = value
        .filter(item => !!item)
        .map(item => item.name)
        .join('/')
    },
    enAreaConfirm(value, index) {
      this.showArea2 = false
      let data = value
        .filter(item => !!item)
        .map(item => item.name)
        .join('/')
      this.addManForm.userInfoBeanList[
        this.selectedIndex
      ].addressProvince = data
    },
    onCodeConfirm(value, index) {
      this.addManForm.userInfoBeanList[index].schoolDistrictId = value.value
      this.addManForm.userInfoBeanList[index].schoolDistrictName = value.name
      this.showCode = false
      let data = {
        code: this.addManForm.userInfoBeanList[index].schoolDistrictId
      }
      getSchoolList(data).then(res => {
        if (res.data.errcode === 0) {
          this.showSchoolColumns = res.data.data
        } else {
          Toast.fail(res.data.msg)
        }
      })
    },
    onSchoolConfirm(value, index) {
      this.addManForm.userInfoBeanList[index].schoolId = value.value
      this.addManForm.userInfoBeanList[index].schoolName = value.name
      this.showSchool = false
      let data = { id: this.addManForm.userInfoBeanList[index].schoolId }
      getClassList(data).then(res => {
        if (res.data.errcode === 0) {
          this.showClassColumns = res.data.data
        } else {
          Toast.fail(res.data.msg)
        }
      })
    },
    onClassConfirm(value, index) {
      this.addManForm.userInfoBeanList[index].classId = value.value
      this.addManForm.userInfoBeanList[index].className = value.name
      this.showClass = false
    },

    goDlConfirm(value) {
      const formatDate = value =>
        `${value.get}/${value.getMonth() + 1}/${value.getDate()}`
      let yy = new Date(value).getFullYear()
      let mm = new Date(value).getMonth() + 1
      let dd = new Date(value).getDate()
      this.formData.estimated_arrival_date = yy + '-' + mm + '-' + dd
      this.goDlShow = false
    },
    onSexConfirm(value) {
      this.label = value
      this.formData.sex = value
      this.showSex = false
    },

    onSubmit() {
      this.$refs.formDataRef
        .validate()
        .then(() => {
          // 验证通过

          if (!this.edit) {
            if (this.addManForm.sysUserBean.password != this.password) {
              Toast.fail('两次密码输入不一致！')
              return
            }
            register(this.addManForm).then(res => {
              Toast.clear()
              if (res.data.errcode === 0) {
                let id =
                  this.$route.query.id != null
                    ? this.$route.query.id
                    : res.data.data.id
                this.$router.push({ name: 'recordQrCode', query: { id: id } })
                Dialog.alert({
                  message: '提交成功',
                  showCancelButton: false,
                  showConfirmButton: false
                }).then(() => {})
                const TIMEOUT = setTimeout(() => {
                  Dialog.close()
                  clearTimeout(TIMEOUT)
                }, 2000)
                this.$router.push({
                  name: '/'
                })
              } else {
                Toast.fail(res.data.msg)
              }
            })
          } else {
            editSysUserInfo(this.addManForm).then(res => {
              Toast.clear()
              if (res.data.errcode === 0) {
                let id =
                  this.$route.query.id != null
                    ? this.$route.query.id
                    : res.data.data.id
                this.$router.push({ name: 'recordQrCode', query: { id: id } })
                Dialog.alert({
                  message: '提交成功',
                  showCancelButton: false,
                  showConfirmButton: false
                }).then(() => {})
                const TIMEOUT = setTimeout(() => {
                  Dialog.close()
                  clearTimeout(TIMEOUT)
                }, 2000)
                this.$router.push({
                  name: 'student-menu'
                })
              } else {
                Toast.fail(res.data.msg)
              }
            })
          }
        })
        .catch(() => {
          // 验证失败
          // Toast.fail(res.data.msg)
          Toast.fail('验证失败')
        })

      // formdata.sex = this.formData.sex=='男'?1:0

      // Toast.loading({
      //   message: '加载中...',
      //   forbidClick: true,
      //   duration: 10000,
      // })
      // helpUserInsert(formdata).then((res) => {
      //   Toast.clear()
      //   if (res.data.errcode === 0) {
      //     let id =
      //       this.$route.query.id != null
      //         ? this.$route.query.id
      //         : res.data.data.id
      //     this.$router.push({ name: 'recordQrCode', query: { id: id } })
      //     Dialog.alert({
      //       message: '提交成功',
      //       showCancelButton: false,
      //       showConfirmButton: false,
      //     }).then(() => {})
      //     const TIMEOUT = setTimeout(() => {
      //       Dialog.close()
      //       clearTimeout(TIMEOUT)
      //     }, 2000)
      //     // 提交成功清空数据
      //     for (let i in this.formData) {
      //       this.formData[i] = ''
      //       this.formData.avenue_flow_area = true
      //     }
      //   } else {
      //     Toast.fail(res.data.msg)
      //   }
      // })
    }
  }
}
</script>
<style lang="less" scoped>
.upload-img-5 {
  margin: 5px 0 90px 0;
}
.upload-img-1 {
  margin: 5px 0 15px 0;
}

.home {
  height: 100%;
  // background: url('../../assets/images/smtb.jpg') no-repeat;

  img {
    // background: url('../../assets/images/smtb.jpg');
    width: 100%;
  }
  .dialog-container {
    height: 70vh;
    overflow-y: auto;
  }
  .get-area {
    width: 100%;
    padding: 0 0.8rem;
    font-size: 0.747rem;
    color: #fff;
    background-color: #1989fa;
    border: 0.053rem solid #1989fa;
    height: 2.347rem;
    line-height: 2.347rem;
    text-align: center;
    border-radius: 0.107rem;
    cursor: pointer;
    box-sizing: border-box;
    margin-right: 10px;
  }
  /deep/.van-field__label {
    width: 8em;
  }
  /deep/.van-field__error-message {
    text-align: right;
  }
  .title {
    // font-size: 28px;
    text-indent: 20px;
    padding: 50px 0 20px;
  }
  .container {
    width: 90%;
    height: 80vh;
    overflow-y: auto;
    border: 1px solid #adadad;
    margin: auto;
    .item {
      margin: 10px;
    }
  }
}
.up-and-down {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f1f3f4;
  height: 80px;
  color: #333;
}
.home .blue {
  background-color: transparent;
}
.home .van-cell {
  background-color: transparent;
}
</style>
